from django.db import models
from django.contrib.auth import get_user_model
from tag.models import Text  # 假设标签应用在tag_app中

User = get_user_model()


class KnowledgeGraph(models.Model):
    """知识图谱元数据"""
    name = models.CharField('图谱名称', max_length=100)
    original_text = models.ForeignKey(
        Text,
        on_delete=models.CASCADE,
        related_name='knowledge_graphs',
        verbose_name='关联文本'
    )
    creator = models.ForeignKey(
        User,
        on_delete=models.CASCADE,
        null=True,
        related_name='knowledge_graphs',
        verbose_name='创建者'
    )
    created_at = models.DateTimeField('创建时间', auto_now_add=True)
    updated_at = models.DateTimeField('更新时间', auto_now=True)
    raw_data = models.JSONField('原始数据', default=dict)

    class Meta:
        verbose_name = '知识图谱'
        verbose_name_plural = verbose_name


class Entity(models.Model):
    """知识实体"""
    ENTITY_TYPES = (
        ('PERSON', '人物'),
        ('ORG', '组织'),
        ('LOC', '地点'),
        ('EVENT', '事件'),
        ('CONCEPT', '概念'),
    )

    name = models.CharField('实体名称', max_length=100)
    type = models.CharField('实体类型', max_length=20, choices=ENTITY_TYPES)
    description = models.TextField('实体描述', blank=True)
    graph = models.ForeignKey(
        KnowledgeGraph,
        on_delete=models.CASCADE,
        related_name='entities',
        verbose_name='所属图谱'
    )
    properties = models.JSONField('扩展属性', default=dict)


class Relationship(models.Model):
    """实体关系"""
    RELATION_TYPES = (
        ('BELONG_TO', '属于'),
        ('LOCATED_IN', '位于'),
        ('PART_OF', '组成部分'),
        ('CAUSE', '导致'),
        ('SIMILAR', '相似于'),
    )

    source = models.ForeignKey(
        Entity,
        on_delete=models.CASCADE,
        related_name='out_relationships',
        verbose_name='源实体'
    )
    target = models.ForeignKey(
        Entity,
        on_delete=models.CASCADE,
        related_name='in_relationships',
        verbose_name='目标实体'
    )
    type = models.CharField('关系类型', max_length=20, choices=RELATION_TYPES)
    weight = models.FloatField('关系强度', default=1.0)
    graph = models.ForeignKey(
        KnowledgeGraph,
        on_delete=models.CASCADE,
        related_name='relationships',
        verbose_name='所属图谱'
    )